<?php


namespace app\api\controller;


use app\BaseController;


//处理redis

use app\Request;
use broadcast\services\UtilService as Util;


//抽奖
use app\models\additional\LuckList;
use app\models\additional\LuckRecord;


use app\models\user\Users;
use app\models\additional\Configine;


// 送礼
use app\models\additional\GiftList;
use app\models\additional\GiftGiving;
use app\models\system\Lecturer;


use broadcast\redis\setRedis;
use Exception;

/**
 * Class Index
 * @package app\api\controller
 */
class Additional extends BaseController
{
    //礼物列表  -- 抽奖
    public function giftList (Request $request)
    {
        session('website', $request->website());
        $uid = $request->uid();
        if (strpos($uid, 'yk') !== false) return app("json")->success('游客状态无法签到');

        $frequency = Configine::where("ident","luck_draw_frequency")->value('value');        //每天抽奖次数
        $explain   = Configine::where("ident","luck_draw_explain")->value('value');          //抽奖说明
        $list = LuckList::alias("l")
        ->join("luck_cate c","c.id=l.cid")
        ->field("c.name,c.images,l.number,l.id")
        ->select();
        if ($list) $list = $list->toArray();
        
        $overdue = setRedis::getCache(session("website"),"luckDrawDay".$uid);

        if ($overdue) {
            if ($overdue['overdue'] == date("Y-m-d")) {
                $signed = $overdue['num'];
            }else{
                $signed = 0;
            }
        }else{
            $signed = 0;
        }

        return app("json")->success(compact('frequency','explain','list','signed'));
    }

    //抽奖  -- 进行
    public function giftLuckDraw(Request $request)
    {
        $data = Util::postMore([
            ['username', ''],           //用户名称
            ['roomid', '']              //房价号                     
        ]);
        session('website', $request->website());
        //用户id
        $uid = $request->uid();


        
        //判断是否可以签到 start

        $frequency = Configine::where("ident","luck_draw_frequency")->value('value');        //每天抽奖次数
        
        $overdue = setRedis::getCache(session("website"),"luckDrawDay".$uid);
        if ($overdue) {
            if ($overdue['overdue'] == date("Y-m-d")) {

                //判断今天是否可以签到
                if ($frequency < $overdue['num']+1) {
                    return app("json")->fail("抽奖次数已用尽");
                }
                setRedis::setCache(session("website"),"luckDrawDay".$uid,['overdue' => date("Y-m-d"),'num' =>$overdue['num'] + 1]);
            }else{
                setRedis::setCache(session("website"),"luckDrawDay".$uid,['overdue' => date("Y-m-d"),'num' => 1]);
            }
        }else {
            setRedis::setCache(session("website"),"luckDrawDay".$uid,['overdue' => date("Y-m-d"),'num' => 1]);
        }

        //判断是否可以签到 end



        //获取抽奖列表
        $list = LuckList::alias("l")
        ->join("luck_cate c","c.id=l.cid")
        ->field("c.name,l.*,c.value")
        ->select();

        $Lotteryprobability = array();

        foreach ($list as $key => $val) {
            $Lotteryprobability[$val['id']] = $val['probability'];
        }


        $luckId = get_rand($Lotteryprobability);

        
        if ($list) $list = $list->toArray();
        //获取奖品类型
        $typeIdList = array_column($list,"name",'id');
        $luckType = $typeIdList[$luckId];

        //获取奖品数量 
        $nuberIdList = array_column($list,"number",'id');
        $luckNumber = $nuberIdList[$luckId];

        //标识
        $valueIdList = array_column($list,"value",'id');
        $luckValue = $valueIdList[$luckId];

        //添加抽奖记录
        $luckrecord = new LuckRecord();
        $luckrecord->save(['roomid'=>$data['roomid'],'uid'=>$uid,"lid"=>$luckId,'username'=>$data['username'],'create_time'=>time(),'luck_name'=>$luckType .' '. $luckNumber]);

        // 判断是不是金钱 start
        if ($luckValue == 'money') 
        {
            $userInfo = setRedis::getUserCache(session("website"), "usersList#" . $uid . ":*");
            $save = Users::where('id', $uid)->inc("balance", (float)$luckNumber)->save();
            if ($userInfo) {
                $userInfo['data']['balance'] = round((float)$userInfo['data']['balance'] + (float)$luckNumber, 2);
                setRedis::setCache(session("website"), "usersList#" . $uid . ":" . $userInfo['data']['username'], $userInfo['data'], 0);
            }
        }
        // 判读是不是金钱 end

        return app("json")->success(['id' => $luckId]);
    }



    //获取当前用户的奖励列表 -- 抽奖
    public function LuckDrawRecord (Request $request) 
    {
        session('website', $request->website());
        $uid = $request->uid();
        $list = LuckRecord::where('uid',$uid)->select();
        if ($list) $list = $list->toArray();
        return app("json")->success($list);
    }



    //获取礼物列表  -- 送礼列表
    public function givingLst(Request $request)
    {
        session('website', $request->website());
        $list = GiftList::field("name,images,price,id")->select();
        if ($list) $list = $list->toArray();
        return app("json")->success($list);
    }

    //送礼
    public function sendGiving (Request $request) 
    {
        $data = Util::postMore([
            ['id', 0],
            ['lecturer',0],
            ['username',''],
            ['number',0]
        ]);
        session('website', $request->website());

        $uid = $request->uid();
        if (strpos($uid, 'yk') !== false) return app("json")->success('游客状态无送礼');

        // 获取礼品
        $info = GiftList::where("id",$data['id'])->find();
        $lectuer = Lecturer::where("id",$data['lecturer'])->value('name');

        if (empty($info)) {
            return app("json")->fail("礼品不存在");
        }

        //总金额
        $totalPrice = (int)$data['number']*(float)$info['price'];
        //消减金额

        try {
            $userInfo = setRedis::getUserCache(session("website"), "usersList#" . $uid . ":*");
            if ((float)$userInfo['data']['balance'] < $totalPrice) {
                return app("json")->fail("用户金额不足");
            }
            $save = Users::where('id', $uid)->dec("balance", (float)$totalPrice)->save();
            if ($userInfo) {
                $userInfo['data']['balance'] = round((float)$userInfo['data']['balance'] - (float)$totalPrice, 2);
                setRedis::setCache(session("website"), "usersList#" . $uid . ":" . $userInfo['data']['username'], $userInfo['data'], 0);
            }
            if ($save) {
                //添加记录
                $GiftGiving = new GiftGiving();
                $GiftGiving->save(['lecturer' => $data['lecturer'],'uid'=>$uid,'username'=>$data['username'],'gift'=>$data['id'],'price'=>$info['price'],'number'=>$data['number'],'total_price'=>(int)$data['number']*(float)$info['price'],'lecturer_name'=>$lectuer]);
                $save = Lecturer::where('id', $uid)->inc("price", (int)$data['number']*(float)$info['price'])->save();
            }
        }catch(Exception $e) {
            return app("json")->fail("送礼失败");
        }
        
        
        return $save ? app("json")->success("送礼成功") : app("json")->fail("送礼失败");
    }


    //获取送礼记录  -- 用户
    public function givingRecord (Request $request)
    {
        session('website', $request->website());

        $uid = $request->uid();

        //获取当前用户的送礼记录

        //获取记录
        $list = GiftGiving::alias("g")
        ->join("gift_list l","l.id=g.gift")
        ->where("uid",$uid)
        ->field("lecturer_name,gift,number,create_time")
        ->select();

        if ($list) $list = $list->toArray();

        return app("json")->success($list);
    }

    // 获取送礼记录 -- 讲师
    public function givingRecords (Request $request) 
    {
        session('website', $request->website());

        $data = Util::postMore([
            ['lecturer',0]
        ]);

        $list = GiftGiving::alias("g")
        ->join("gift_list l","l.id=g.gift")
        ->where("lecturer",$data['lecturer'])
        ->field("lecturer_name,gift,number,create_time")
        ->select();

        if ($list) $list = $list->toArray();

        return app("json")->success($list);
        
    }

}